<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span class="active">居民列表</span>
    </div>

    <el-row :gutter="24">
      <el-col :span="24">
        <span>楼栋：</span>
        <CasCader @handleChange="handleChange"></CasCader>
        <span>姓名：</span>
        <el-input style="width: 15%;" v-model="form.name" placeholder="请输入姓名" clearable></el-input>
        <span>电话：</span>
        <el-input style="width: 15%;" v-model="form.mobile" placeholder="请输入电话" clearable></el-input>
        <span>房间号：</span>
        <el-input style="width: 15%;" v-model="form.room" placeholder="请输入房间号" clearable></el-input>

        <span>居民类型:</span>
        <el-select style="width: 15%;" v-model="form.userType" placeholder="请选择居民类型" clearable>
          <el-option v-for="item in userTypeOptions" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>

        <el-button type="primary" @click="handleQuery">查询</el-button>
      </el-col>
    </el-row>

    <el-row style="margin: 20px 0;">
      <el-button type="primary" @click="handleAdd">添加</el-button>
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
      <el-button type="success" @click="handleBatchAudit">批量审核</el-button>
    </el-row>

    <!-- 表格 -->
    <BaseTable :tableColumn="tableColumn" :tableData="tableData" :loading="loading" :isShowSelection="true"
      @selection-change="handleSelectionChange">

      <template #options="{ row }">
        <el-button @click="handleEdit(row)" type="success" size="mini">修改</el-button>
        <el-button size="mini" @click="handleDelete(row)" type="danger">删除</el-button>
      </template>
      
    </BaseTable>

    <!-- 分页 -->
    <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="query.page" :page-sizes="[5, 10, 20, 50]" :page-size="query.psize"
      layout="total, sizes, prev, pager, next, jumper" :total="counts">
    </el-pagination>

    <!-- 编辑 -->
    <Dialoguserinfo :dialogVisible="dialogVisible" :isEdit="isEdit" :editData="editData" @handleCancel="handleCancel"
      @refreshList="refreshList"></Dialoguserinfo>
  </el-card>
</template>

<script>
import { list, del, userinfotype, delall } from '../api/userinfo';
import Dialoguserinfo from '../components/DialogUserinfo.vue';
import BaseTable from './BaseTable.vue';
import CasCader from '../components/CasCader.vue';
// import { miXinPower } from "@/utils/miXinPower.js";

export default {
  name: 'UserinfoView',
  components: {
    BaseTable,
    CasCader,
    Dialoguserinfo
  },
  // mixins: [miXinPower],

  data() {
    return {
      dialogVisible: false,
      isEdit: false,
      loading: true,
      editData: {},

      tableColumn: [
        {
          prop: "id",
          label: "ID",
        },
        {
          prop: "photo",
          label: "头像",
          slotname: 'logo',
        },
        {
          prop: "name",
          label: "姓名",
        },
        {
          prop: "usertypeName",
          label: "类型",
        },
        {
          prop: "sex",
          label: "性别",
        },
        {
          prop: "cardid",
          label: "身份证号",
        },
        {
          prop: "mobile",
          label: "手机号",
        },
        {
          prop: "usernative",
          label: "籍贯",
        },
        {
          prop: "nation",
          label: "民族",
        },
        {
          prop: "building",
          label: "小区",
        },
        {
          prop: "houseno",
          label: "房间号",
        },
        {
          prop: "options",
          label: "操作",
          width: 180,
          slotname: "options",
        },
      ],

      // 查询表单
      form: {
        building: '',
        name: '',
        mobile: '',
        room: '',
        userType: ''
      },

      // 查询参数
      query: {
        page: 1,
        psize: 10,
        buildingid: '',
        name: '',
        mobile: '',
        room: '',
        userType: ''
      },
      // 居民类型选项
      userTypeOptions: [],
      tableData: [],
      counts: 0,
      selectedRows: []
    }
  },

  created() {
    this.getList()
    this.getUserinfoTypeList()
  },

  methods: {
    async getList() {
      this.loading = true;
      try {
        // 合并查询参数
        const params = {
          ...this.query,
          page: this.query.page,
          psize: this.query.psize
        };

        let { data: { counts, list: listData } } = await list(params);
        this.counts = counts;
        this.tableData = listData;
        this.loading = false;
      } catch (error) {
        console.error('获取数据失败:', error);
        this.$message.error('获取居民列表失败');
      }
    },
    
    getFullImageUrl(url) {
      if (!url) return '';
      if (url.startsWith('http')) return url;
      return `${process.env.VUE_APP_UPLOAD_BASE_URL}${url}`;
    },

    async getUserinfoTypeList() {
      try {
        let { data: { list: listData } } = await userinfotype();

        console.log('获取到的居民类型:', listData);
        this.userTypeOptions = listData;
      } catch (error) {
        console.error('获取居民类型失败:', error);
        this.$message.error('获取居民类型失败');
      }
    },

    async handleDelete(row) {
      try {
        await this.$confirm('此操作将永久删除该居民信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await del({ id: row.id })
        await this.getList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      } catch (error) {
        if (error === 'cancel') {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        } else {
          console.error('删除失败:', error)
          this.$message.error('删除失败');
        }
      }
    },
    handleChange(buildingarr) {
      // console.log(val)
      this.query.buildingid = buildingarr.length ? buildingarr[buildingarr.length - 1] : ''
    },

    handleEdit(row) {
      this.editData = { ...row };
      this.isEdit = true;
      this.dialogVisible = true;
    },

    handleAdd() {
      this.isEdit = false;
      this.dialogVisible = true;

    },

    handleBatchDelete() {
      console.log(this.selectedRows);
      if (!this.selectedRows.length) return this.$message.error('请选择要删除的记录');
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        let ids = this.selectedRows.map(item => item.id);
        await delall({ ids: ids });
        await this.getList();
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.info('已取消删除');
      })
    },

    handleBatchAudit() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请至少选择一条记录');
        return;
      }

      this.$message.info(`已选择${this.selectedRows.length}条记录进行审核`);
    },
    handleCancel() {
      this.dialogVisible = false;
      this.isEdit = false;
    },
    refreshList() {
      this.dialogVisible = false;
      this.isEdit = false;
      this.query.page = 1;
      this.getList();
    },

    // 添加selection change事件处理器
    handleSelectionChange(val) {
      this.selectedRows = val;
    },

    handleSizeChange(val) {
      this.query.psize = val;
      this.query.page = 1;
      this.getList();
      console.log(`每页 ${val} 条`);
    },

    handleCurrentChange(val) {
      this.query.page = val;
      this.getList();
      console.log(`当前页: ${val}`);
    },

    // 查询功能
    handleQuery() {
      this.query.page = 1;
      this.getList();
    },
  }
}
</script>

<style lang="less" scoped>
@import url(../assets/css/userinfo.less);

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>